<template>
  <div
    class="notice-bar flex items-center border-1 rounded-4px px-12px py-8px overflow-hidden whitespace-nowrap transition-all-300"
    :style="{
      backgroundColor: theme.bgColor,
      borderColor: theme.borderColor,
      color: theme.textColor,
      fontSize: fontSize + 'px'
    }"
  >
    <n-icon class="notice-icon mr-8px flex-shrink-0 text-16px" :style="{ color: theme.iconColor }">
      <chat-dot-round />
    </n-icon>
    <div class="notice-text-wrapper flex-1 overflow-hidden mr-8px">
      <div
        class="notice-text inline-block pl-100% whitespace-nowrap"
        :class="{ 'no-scroll': !enableScroll }"
        :style="{
          animationDuration: duration + 's',
          fontSize: fontSize + 'px'
        }"
        v-html="text"
      ></div>
    </div>
    <n-button
      text
      class="history-button flex-shrink-0 text-12px rounded-4px"
      :style="{ color: theme.iconColor }"
      @click="showHistoryDialog = true"
    >
      <template #icon>
        <n-icon>
          <bell />
        </n-icon>
      </template>
      历史公告
    </n-button>
  </div>

  <!-- 历史公告弹窗 -->
  <n-modal
    v-model:show="showHistoryDialog"
    preset="dialog"
    title="历史公告"
    :style="{ width: '60%' }"
    class="history-dialog"
  >
    <div class="history-list max-h-400px overflow-y-auto">
      <n-empty v-if="sortedNotices.length === 0" description="暂无历史公告" />
      <div v-else>
        <div
          v-for="(notice, index) in sortedNotices"
          :key="index"
          class="history-item border-1 border-solid border-#e8e8e8 rounded-6px p-12px mb-12px bg-#fafafa transition-all-300 hover:bg-#f0f0f0 hover:border-#d9d9d9"
          :class="{ 'pinned-item': notice.pinned }"
        >
          <!-- 置顶标签 -->
          <div
            v-if="notice.pinned"
            class="pinned-tag absolute top--1px left--1px bg-#f56c6c text-white text-12px font-500 px-6px py-2px z-1 leading-none"
          >
            置顶
          </div>

          <div
            class="history-content text-14px leading-1.6 text-#333 break-all my-8px py-8px"
            :class="{ 'mt-20px': notice.pinned }"
            v-html="notice.content"
          ></div>

          <div class="history-header flex justify-between items-center mb-8px">
            <span class="history-date text-12px text-#999">{{ notice.date }}</span>
            <n-tag
              size="small"
              round
              :style="{
                backgroundColor: getCategoryColor(notice.category),
                borderColor: getCategoryColor(notice.category),
                color: '#fff'
              }"
            >
              {{ notice.category || '公告' }}
            </n-tag>
          </div>
        </div>
      </div>
    </div>

    <template #action>
      <n-button @click="showHistoryDialog = false">关闭</n-button>
    </template>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { NIcon, NButton, NModal, NEmpty, NTag } from 'naive-ui'
import {
  ChatbubbleEllipsesOutline as ChatDotRound,
  NotificationsOutline as Bell
} from '@vicons/ionicons5'

interface Notice {
  content: string
  date: string
  type?: string
  category?: string
  pinned?: boolean
}

const props = withDefaults(
  defineProps<{
    text: string
    duration?: number // 滚动一圈耗时（秒）
    themeType?: 'warning' | 'info' | 'success' | 'error' // 主题配置
    enableScroll?: boolean // 是否启用滚动
    fontSize?: number // 字体大小
    historyNotices?: Notice[] // 历史公告数据
    categoryColors?: Record<string, string> // 分类颜色配置
  }>(),
  {
    duration: 10,
    themeType: 'warning',
    enableScroll: true,
    fontSize: 14,
    historyNotices: () => [],
    categoryColors: () => ({})
  }
)

const emit = defineEmits<{
  'clear-history': []
  'add-to-history': [notice: Notice]
}>()

// 弹窗控制
const showHistoryDialog = ref(false)

// 主题配置
const themes = {
  warning: {
    bgColor: '#fffbe6',
    borderColor: '#ffe58f',
    textColor: '#666',
    iconColor: '#faad14'
  },
  info: {
    bgColor: '#e6f7ff',
    borderColor: '#91d5ff',
    textColor: '#666',
    iconColor: '#1890ff'
  },
  success: {
    bgColor: '#f6ffed',
    borderColor: '#b7eb8f',
    textColor: '#666',
    iconColor: '#52c41a'
  },
  error: {
    bgColor: '#fff2f0',
    borderColor: '#ffccc7',
    textColor: '#666',
    iconColor: '#ff4d4f'
  }
}

const theme = computed(() => themes[props.themeType] || themes.warning)

// 获取分类颜色
const getCategoryColor = (category?: string): string =>
  (category && props.categoryColors[category]) || '#909399'

// 处理置顶排序的计算属性
const sortedNotices = computed(() => {
  if (!props.historyNotices || props.historyNotices.length === 0) {
    return []
  }

  // 将公告分为置顶和普通两组
  const pinnedNotices = props.historyNotices.filter((notice) => notice.pinned)
  const normalNotices = props.historyNotices.filter((notice) => !notice.pinned)

  // 置顶公告在前，然后是普通公告
  return [...pinnedNotices, ...normalNotices]
})

// 添加新公告到历史记录
const addToHistory = (notice: Notice | string): void => {
  const newNotice: Notice = {
    content: typeof notice === 'string' ? notice : notice.content || '',
    date: new Date().toLocaleString('zh-CN'),
    type: typeof notice === 'string' ? 'info' : notice.type || 'info',
    category: typeof notice === 'string' ? '公告' : notice.category || '公告'
  }
  emit('add-to-history', newNotice)
}

// 暴露方法给父组件
defineExpose({
  addToHistory,
  showHistory: () => (showHistoryDialog.value = true)
})
</script>

<style scoped>
.notice-bar {
  transition: all 0.3s ease;
}

.notice-text {
  animation: scroll-left linear infinite;
}

.notice-text :deep(a) {
  color: inherit;
  text-decoration: underline;
  cursor: pointer;
}

.notice-text :deep(a:hover) {
  opacity: 0.8;
}

.notice-text.no-scroll {
  animation: none;
  padding-left: 0;
  width: 100%;
  text-overflow: ellipsis;
  overflow: hidden;
}

.history-button {
  transition: all 0.3s ease;
}

.history-button:hover {
  background-color: rgba(0, 0, 0, 0.04);
}

.history-item:last-child {
  margin-bottom: 0;
}

.history-content :deep(a) {
  color: #1890ff;
  text-decoration: none;
  cursor: pointer;
}

.history-content :deep(a:hover) {
  text-decoration: underline;
  opacity: 0.8;
}

/* 置顶公告样式 */
.pinned-item {
  position: relative;
  background-color: #e6f7ff !important;
  border-color: #91d5ff !important;
}

/* 滚动动画 */
@keyframes scroll-left {
  0% {
    transform: translateX(0%);
  }
  100% {
    transform: translateX(-100%);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notice-bar {
    padding: 6px 8px;
  }
}
</style>
